#include "HashMap.h"
#include <stdlib.h>
#include <stdio.h>

// 哈希函数
static int hash(int key, int capacity) {
    return key % capacity;
}

// 创建哈希表
HashMap* create_hashmap(int capacity) {
    HashMap* map = (HashMap*)malloc(sizeof(HashMap));
    if (map == NULL) {
        perror("Failed to create hashmap");
        return NULL;
    }
    map->buckets = (KeyValue**)calloc(capacity, sizeof(KeyValue*));
    if (map->buckets == NULL) {
        perror("Failed to create hashmap buckets");
        free(map);
        return NULL;
    }
    map->capacity = capacity;
    map->size = 0;
    return map;
}

// 销毁哈希表
void destroy_hashmap(HashMap* map) {
    if (map == NULL) return;
    for (int i = 0; i < map->capacity; i++) {
        KeyValue* node = map->buckets[i];
        while (node != NULL) {
            KeyValue* tmp = node;
            node = node->next;
            free(tmp);
        }
    }
    free(map->buckets);
    free(map);
}

// 插入键值对
bool hashmap_put(HashMap* map, int key, int value) {
    int index = hash(key, map->capacity);
    KeyValue* node = map->buckets[index];
    while (node != NULL) {
        if (node->key == key) {
            node->value = value;
            return true;
        }
        node = node->next;
    }
    node = (KeyValue*)malloc(sizeof(KeyValue));
    if (node == NULL) {
        perror("Failed to insert into hashmap");
        return false;
    }
    node->key = key;
    node->value = value;
    node->next = map->buckets[index];
    map->buckets[index] = node;
    map->size++;
    return true;
}

// 查找键值对
bool hashmap_get(HashMap* map, int key, int* value) {
    int index = hash(key, map->capacity);
    KeyValue* node = map->buckets[index];
    while (node != NULL) {
        if (node->key == key) {
            *value = node->value;
            return true;
        }
        node = node->next;
    }
    return false;
}

// 删除键值对
bool hashmap_remove(HashMap* map, int key) {
    int index = hash(key, map->capacity);
    KeyValue* node = map->buckets[index];
    KeyValue* prev = NULL;
    while (node != NULL) {
        if (node->key == key) {
            if (prev == NULL) {
                map->buckets[index] = node->next;
            } else {
                prev->next = node->next;
            }
            free(node);
            map->size--;
            return true;
        }
        prev = node;
        node = node->next;
    }
    return false;
}

// 获取哈希表大小
int hashmap_size(HashMap* map) {
    return map->size;
}
